package leetcode.Y2024M6.study;

import leetcode.Y2024M6.TreeNode;
import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 可以好好看下
 */
public class S103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            LinkedList<Integer> nodeList = new LinkedList<>();
            for (; size > 0; size--) {
                TreeNode node = queue.poll();
                // 利用奇偶特点以及链表的特点
                if (res.size() % 2 == 0) nodeList.addLast(node.val);
                else nodeList.addFirst(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            res.add(nodeList);
        }
        return res;
    }

    @Test
    public void test() {
        int[] root = {3, 9, 20, -1, -1, 15, 7};
        System.out.println(zigzagLevelOrder(TreeNode.createTree(root)));
    }
}
